package com.taskmanagement.controller;

import com.taskmanagement.entity.Step;
import com.taskmanagement.service.StepService;
import com.taskmanagement.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/steps")
public class StepController {

    @Autowired
    private StepService stepService;
    
    @Autowired
    private TaskService taskService;

    @GetMapping("/task/{taskId}")
    public ResponseEntity<?> getStepsByTaskId(@PathVariable BigInteger taskId) {
        try {
            BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(taskId, userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            List<Step> steps = stepService.findByTaskId(taskId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", steps);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/task/{taskId}")
    public ResponseEntity<?> createStep(@PathVariable BigInteger taskId, @RequestBody Step step) {
        try {
            BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(taskId, userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            step.setTaskId(taskId);
            Step createdStep = stepService.createStep(step);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "步骤添加成功");
            response.put("data", createdStep);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateStep(@PathVariable BigInteger id, @RequestBody Step step) {
        try {
            Step existingStep = stepService.findById(id);
            if (existingStep == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "步骤不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(existingStep.getTaskId(), userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无权操作此步骤");
                return ResponseEntity.badRequest().body(response);
            }
            
            step.setId(id);
            step.setTaskId(existingStep.getTaskId());
            Step updatedStep = stepService.updateStep(step);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "步骤更新成功");
            response.put("data", updatedStep);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteStep(@PathVariable BigInteger id) {
        try {
            Step existingStep = stepService.findById(id);
            if (existingStep == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "步骤不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(existingStep.getTaskId(), userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无权操作此步骤");
                return ResponseEntity.badRequest().body(response);
            }
            
            boolean deleted = stepService.deleteStep(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "步骤删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateStepStatus(@PathVariable BigInteger id, @RequestBody Map<String, Boolean> statusRequest) {
        try {
            Step existingStep = stepService.findById(id);
            if (existingStep == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "步骤不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
           BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(existingStep.getTaskId(), userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无权操作此步骤");
                return ResponseEntity.badRequest().body(response);
            }
            
            Boolean isCompleted = statusRequest.get("isCompleted");
            boolean updated = stepService.updateStepStatus(id, isCompleted);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "步骤状态更新成功");
            response.put("data", new HashMap<String, Object>() {{
                put("id", id);
                put("isCompleted", isCompleted);
                put("actualEndDate", isCompleted ? new Date() : null);
            }});
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    private BigInteger getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        return taskService.findByUsername(username).getId();
    }
}
